package com.gambi.example.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.Dictionary;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.visualization.client.VisualizationUtils;
import com.google.gwt.visualization.client.visualizations.AnnotatedTimeLine;
import com.google.gwt.visualization.client.visualizations.Gauge;
import com.google.gwt.visualization.client.visualizations.LineChart;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public abstract class GWTTapestry implements EntryPoint {

	/**
	 * This is the entry point method.
	 */

	public void onModuleLoad() {

		GWT.log("GWTTapestry.onModuleLoad()");
		try {
			// Get the js Namespace object for this entryPoint
			Dictionary config = Dictionary.getDictionary(getName());
			// Get the entry that contains completeIDs for the Tapestry
			// Components that host the GWT widgets
			String[] ids = config.get("componentIDs").split(",");
			if (ids == null) {
				// No widgets, no work. We have done.
				return;
			}

			// This ensure that your browser loads all the required libraries BEFORE your widgets use them.
			// TODO can we "split" the widgets to avoid this every time ? How do we ensure that all the libraries will be listed here ?
			Runnable onLoadCallback = new myRunnable(ids);
			VisualizationUtils.loadVisualizationApi(onLoadCallback,AnnotatedTimeLine.PACKAGE, LineChart.PACKAGE, Gauge.PACKAGE);

		} catch (Throwable e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	class myRunnable implements Runnable {
		private String[] ids;

		public myRunnable(String[] ids) {
			this.ids = ids;
		}

		public void run() {
			for (String id : ids) {
				Composite w = widgetFactory(id);
				if (w != null) {
					RootPanel.get(id).add(w);
				}
			}

		}

	}

	public String getName() {
		return this.getClass().getName().replace(".", "");
	}

	// TODO This must be implemented by the sub classes. Can we Contribute to
	// Someone while creating a new component library
	// TODO Shall we define a EntryPointSource or something ?
	public abstract Composite widgetFactory(String id);
}
